package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.app.util.FreemarkerUtil;
import cn.wolfcode.trip.base.domain.Region;
import cn.wolfcode.trip.base.domain.Strategy;
import cn.wolfcode.trip.base.mapper.RegionMapper;
import cn.wolfcode.trip.base.query.StrategyQueryObject;
import cn.wolfcode.trip.base.query.TravelQueryObject;
import cn.wolfcode.trip.base.service.IRegionService;
import cn.wolfcode.trip.base.service.IStrategyService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.spi.http.HttpContext;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController()
@RequestMapping("/regions")
public class RegionController {
    @Autowired
    private IRegionService service;
    @Autowired
    private IStrategyService strategyService;
    @Autowired
    private ServletContext ctx;
    @Autowired
    private RegionMapper regionMapper;


    @GetMapping()
    public Object queryTravels(TravelQueryObject qo) {
        qo.setOrderBy("lastUpdateTime desc");
        List<Region> list = service.selectAll();
        return list;
    }

    /*
      查询热门区域
      动作:GET
      资源:/regions/hots
     参数:state=1

      @param state
      @return
     */
    @GetMapping("/hots")
    public Object getHot(Integer state) {
        List<Region> list = service.listHot(state);
        return list;
    }

    /*
      查询当前区域攻略
      动作:GET
      资源:/regions/{id}/strategies
      参数:

      @return*/

    @GetMapping("/{placeId}/strategies")
    public void getStrategy(StrategyQueryObject qo, HttpServletResponse resp) throws Exception {
        resp.setContentType("text/html;charset=utf-8");
        String dir = ctx.getRealPath("/template");
        Map<String, Object> map = new HashMap<>();
        //查询当前区域的所有攻略,需要分页
        PageInfo<Strategy> info = strategyService.selectList(qo);
        map.put("info", info);
        if (qo.getCurrentPage() != 1){
            FreemarkerUtil.wirteTempDate(dir,"classify.ftl",map,resp.getWriter());
            return;
        }
        //查询当前区域的推荐攻略,不用分页
        qo.setPageSize(0);
        qo.setState(Strategy.STATE_COMMEND);
        List<Strategy> list = strategyService.selectList(qo).getList();
        map.put("id", qo.getPlaceId());
        map.put("commends", list);
        FreemarkerUtil.wirteTempDate(dir, "strategyContent.ftl", map, resp.getWriter());
    }

    /*查询城市
    动作:GET
    资源:/regions/cities
    参数:*/

    @GetMapping("/cities")
    public Object getCities() {

        return regionMapper.selectByParentId();
    }


}
